package com.diankangwo.controller;

import com.diankangwo.constant.PayStatus;
import com.diankangwo.constant.resultMsg;
import com.diankangwo.dao.*;
import com.diankangwo.domain.*;
import com.diankangwo.util.GuidUtil;
import com.diankangwo.util.OrderUtil;
import com.diankangwo.util.PageSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.dao.ReflectionSaltSource;
import org.springframework.security.authentication.encoding.ShaPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.*;

/**
 * 端口控制器
 *
 * @author xiaoyu
 */
@Controller
@Api(description = "端口")
public class PortController {

    @Autowired
    private UserDAO userDao;

    @Autowired
    private PortDAO portDao;

    @Autowired
    private PortPayLogDAO portPayLogDAO;

    @Autowired
    private PortSettingDAO portSettingDAO;

    @Autowired
    private OrderDAO orderDAO;

    @Autowired
    private OnlinePayLogDAO onlinePayLogDAO;

    @Resource
    private ReflectionSaltSource saltSource;

    @Resource
    private ShaPasswordEncoder passwordEncoder;

    /**
     * 获取端口列表
     *
     * @param accessToken token
     * @param type        可选 mine / saleing
     * @return
     */
    @ApiOperation(value = " 获取端口列表", notes = "")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "accessToken", value = "token", required = true, dataType = "String"),
            @ApiImplicitParam(name = "type", value = "可选 mine / saleing", required = true, dataType = "String")
    })
    @ResponseBody
    @RequestMapping(value = "/ports", method = RequestMethod.GET)
    public String show(String accessToken, String type, int pageNo, int pageSize) {
        UserInfo user = userDao.getUserByToken(accessToken);
        String code = "2";
        String msg = "处理异常！";
        PageSupport<Port> pList = new PageSupport<>();
        if (user != null) {
            if (type.equals("saleing")) {
                pList = portDao.findByType(type, pageNo, pageSize);
            } else {
                pList = portDao.findByUser(user.getId(), pageNo, pageSize);
            }
            code = "1";
            if (pList != null) {
                msg = "查询成功！";
            } else {
                msg = "未查询到数据！";
                return resultMsg.mapToJson(code, msg, null);
            }
        } else {
            msg = "未查询到用户信息！";
        }
        return resultMsg.mapToJson(code, msg, pList.getResultData() == null ? null : pList.getResultData());
    }

    /**
     * 获取端口信息
     *
     * @param accessToken token
     * @return
     */
    @ApiOperation(value = " 获取端口信息", notes = "")
    @ApiImplicitParam(name = "accessToken", value = "token", required = true, dataType = "String")
    @ResponseBody
    @RequestMapping(value = "/ports/one/get", method = RequestMethod.GET)
    public String one(String accessToken, Integer id) {
        UserInfo user = userDao.getUserByToken(accessToken);
        String code = "2";
        String msg = "处理异常！";
        Port pList = null;
        if (user != null) {
            code = "1";
            msg = "查询成功！";
            pList = portDao.find(id);
        } else {
            msg = "未查询到用户信息！";
        }
        return resultMsg.mapToJson(code, msg, pList);
    }

    /**
     * 获取端口信息
     */
    @ApiOperation(value = " 获取端口信息", notes = "")
    @ResponseBody
    @RequestMapping(value = "/ports/oneByNotToken", method = RequestMethod.GET)
    public String oneByNotToken(Integer id) {
        String code = "1";
        String msg = "成功！";
        Port pList = null;
        pList = portDao.find(id);
        return resultMsg.mapToJson(code, msg, pList);
    }


    /**
     * 申请端口
     *
     * @param accessToken token
     * @param tel         手机号
     * @param IDCard      身份证
     * @param name        姓名
     * @return
     */
    @ApiOperation(value = " 申请端口", notes = "")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "accessToken", value = "token", required = true, dataType = "String"),
            @ApiImplicitParam(name = "tel", value = "手机号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "IDCard", value = "身份证", required = true, dataType = "String"),
            @ApiImplicitParam(name = "name", value = "姓名", required = true, dataType = "String")
    })
    @ResponseBody
    @RequestMapping(value = "/ports/one", method = RequestMethod.POST)
    public String one(String accessToken, String tel, String IDCard, String name) {
        UserInfo user = userDao.getUserByToken(accessToken);
        String code = "2";
        String msg = "处理异常！";
        Order order = new Order();
        if (user != null) {

            //为订单赋值
            order.setUid(user.getUid());
            order.setUid(user.getUid());
            order.setCreateDate(new Date());
            order.setOrderNo(OrderUtil.getOrderNo());
            order.setCoiUid(GuidUtil.getGuid());
            order.setOrderStatus(PayStatus.unpaid.getName());
            order.setOrderNo(OrderUtil.getOrderNo());
            order.setUpdateDate(new Date());
            order.setUpdateUser(user.getUsername());
            order.setIsPay("0");
            order.setUserName(user.getUsername());
            order.setUserPhone(user.getTel());
            order.setProvince("");
            order.setProvinceID(0);
            order.setCity("");
            order.setCityID(0);
            order.setArea("");
            order.setAreaID(0);
            order.setAddress("");
            order.setOrderChanel("申请端口");
            if (user.isPort()) {
                order.setTotalFee((int) (portSettingDAO.findAll().get(0).getUserprice() * 100));
            } else {
                order.setTotalFee((int) (portSettingDAO.findAll().get(0).getPortPrice() * 100));
            }
            order.setType("port");
            order = orderDAO.saveOrUpdate(order);

            //存入支付数据
            OnlinePayLog opl = new OnlinePayLog();
            opl.setCreateDate(new Date());
            opl.setBillNo(order.getOrderNo());
            opl.setCreateUser(user.getUsername());
            opl.setIdKey(GuidUtil.getGuid());
            opl.setPayStatus(PayStatus.unpaid.getName());
            opl.setPayType(order.getPayType());
            opl.setTitle("申请端口");
            opl.setTotalFee(order.getTotalFee());
            onlinePayLogDAO.saveOrUpdate(opl);

//            //查询当前端口设置
//            PortSetting portSetting = portSettingDAO.findAll().get(0);
//            Port p = new Port();
//            p.setUserId(user.getId());
//            p.setTel(tel);
//            p.setId_card(IDCard);
//            p.setName(name);
//            p.setPortId(GuidUtil.getGuid());
//            p.setPresent_value(portSetting.getPortPrice());
//            p.setSaleing(0);
//            p.setPrice(portSetting.getPortTransferPrice());
//            p.setSource("申请端口");
//            p.setMoney(portSetting.getPortPrice());
//            p.setAdminName(user.getName());
//            p.setAdminPhone(user.getTel());
//            p.setReviewStatus("未审核");
//            p.setBuytime(new Date());
//            portDao.saveOrUpdate(p);
            code = "1";
            msg = "申请成功！";
        } else {
            msg = "未查询到用户信息！";
        }
        return resultMsg.mapToJson(code, msg, order);
    }

    /**
     * 出售/转让端口
     *
     * @param accessToken token
     * @param portID      端口ID
     * @param type        类型
     * @param FName       好友姓名
     * @param FIDCard     好友身份证
     * @param FTel        好友手机号
     * @return
     */
    @ApiOperation(value = " 出售/转让端口", notes = "")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "accessToken", value = "token", required = true, dataType = "String"),
            @ApiImplicitParam(name = "portID", value = "端口ID", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "type", value = "类型", required = true, dataType = "String"),
            @ApiImplicitParam(name = "FName", value = "被转让人名称", required = true, dataType = "String"),
            @ApiImplicitParam(name = "FIDCard", value = "被转让人身份证号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "FTel", value = "被转让人电话号码", required = true, dataType = "String")
    })
    @ResponseBody
    @RequestMapping(value = "/ports/one/put", method = RequestMethod.POST)
    public String one(String accessToken, Integer portID, String type, String FName, String FIDCard, String FTel, String PayPassWord) {
        UserInfo user = userDao.getUserByToken(accessToken);
        String code = "2";
        String msg = "处理异常！";
        if (user != null) {
            PayPassWord = passwordEncoder.encodePassword(PayPassWord, saltSource.getSalt(user));
            if (PayPassWord.equals(user.getPayPwd())) {
                if (type.equals("offline")) {
                    Port p = portDao.findByPortId(portID);
                    UserInfo u = userDao.getUserByTel(FTel);
                    if (u == null) {
                        msg = "该用户不存在！";
                        return resultMsg.mapToJson(code, msg, null);
                    }
                    p.setSource("offline");
                    p.setTel(u.getTel());
                    p.setName(FName);
                    p.setId_card(FIDCard);
                    p.setType("offline");
                    p.setSaleing(0);
                    p.setParentId(user.getId());
                    p.setUserId(u.getId());
                    u.setPort(true);
                    userDao.saveOrUpdate(u);
                    p.setBuytime(new Date());
                    PortPayLog portPayLog = new PortPayLog();
                    portPayLog.setPrice(p.getPresent_value() * 100);
                    portPayLog.setUserId(user.getId());
                    portPayLog.setPortId(p.getId());
                    portPayLog.setStates("offline");
                    portPayLog.setDate(new Date());
                    portPayLog.setType("0");
                    portPayLogDAO.saveOrUpdate(portPayLog);
                    if (portDao.saveOrUpdate(p) != null) {
                        code = "1";
                        msg = "转让成功！";
                        if (portDao.findByUser(user.getId(), 1, Integer.MAX_VALUE) == null || portDao.findByUser(user.getId(), 1, Integer.MAX_VALUE).getResultData().size() == 0) {
                            user.setPort(false);
                            userDao.saveOrUpdate(user);
                        }
                    } else {
                        msg = "系统异常，转让失败！";
                    }
                } else {
                    Port p = portDao.findByPortId(portID);
                    p.setSource("online");
                    p.setType("online");
                    p.setSaleing(1);
                    p.setParentId(user.getId());
                    if (portDao.saveOrUpdate(p) != null) {
                        code = "1";
                        msg = "转让成功！";
                        if (portDao.findByUser(user.getId(), 1, Integer.MAX_VALUE) == null || portDao.findByUser(user.getId(), 1, Integer.MAX_VALUE).getResultData().size() == 0) {
                            user.setPort(false);
                            userDao.saveOrUpdate(user);
                        }
                    } else {
                        msg = "系统异常，转让失败！";
                    }
                }
            } else {
                msg = "支付密码不正确！";
            }
        } else {
            msg = "未查询到用户信息！";
        }
        return resultMsg.mapToJson(code, msg, null);
    }

    /**
     * 主动/被动(同意)/拒绝购买端口
     *
     * @param accessToken token
     * @return
     */
    @ApiOperation(value = " 主动/被动(同意)/拒绝购买端口", notes = "")
    @ResponseBody
    @RequestMapping(value = "/ports/one/buy", method = RequestMethod.POST)
    public String buy(String accessToken) {
        UserInfo user = userDao.getUserByToken(accessToken);
        String code = "2";
        String msg = "处理异常！";
        Order order = new Order();
        if (user != null) {
            //为订单赋值
            order.setUid(user.getUid());
            order.setUid(user.getUid());
            order.setCreateDate(new Date());
            order.setOrderNo(OrderUtil.getOrderNo());
            order.setCoiUid(GuidUtil.getGuid());
            order.setOrderStatus(PayStatus.unpaid.getName());
            order.setOrderNo(OrderUtil.getOrderNo());
            order.setUpdateDate(new Date());
            order.setUpdateUser(user.getUsername());
            order.setIsPay("0");
            order.setUserName(user.getUsername());
            order.setUserPhone(user.getTel());
            order.setProvince("");
            order.setProvinceID(0);
            order.setCity("");
            order.setCityID(0);
            order.setArea("");
            order.setAreaID(0);
            order.setAddress("");
            order.setOrderChanel("购买端口");
//            if (user.isPort()) {
//                order.setTotalFee((int) (portSettingDAO.findAll().get(0).getUserprice() * 100));
//            } else {
            order.setTotalFee((int) (portSettingDAO.findAll().get(0).getPortPrice() * 100));
//            }

            order.setType("port");
            order = orderDAO.saveOrUpdate(order);

            //存入支付数据
            OnlinePayLog opl = new OnlinePayLog();
            opl.setCreateDate(new Date());
            opl.setBillNo(order.getOrderNo());
            opl.setCreateUser(user.getUsername());
            opl.setIdKey(GuidUtil.getGuid());
            opl.setPayStatus(PayStatus.unpaid.getName());
            opl.setPayType(order.getPayType());
            opl.setTitle("购买端口");
            opl.setTotalFee(order.getTotalFee());
            onlinePayLogDAO.saveOrUpdate(opl);
            code = "1";
            msg = "购买成功！";
        } else {
            msg = "未查询到用户信息！";
        }
        return resultMsg.mapToJson(code, msg, order);
    }

    /**
     * 获取我的端口交易日志
     *
     * @param accessToken token
     * @return
     */
    @ApiOperation(value = " 获取我的端口交易日志", notes = "")
    @ApiImplicitParam(name = "accessToken", value = "token", required = true, dataType = "String")
    @ResponseBody
    @RequestMapping(value = "/ports/log", method = RequestMethod.GET)
    public String payLog(String accessToken, int pageNo, int pageSize) {
        UserInfo user = userDao.getUserByToken(accessToken);
        String code = "2";
        String msg = "处理异常！";
        List<PortPayLog> portPayLog = new ArrayList<PortPayLog>();
        if (user != null) {
            user.setPassword("");
            user.setSalt_value("");
            code = "1";
            portPayLog = portPayLogDAO.findPagination("from PortPayLog where userId = ?", pageNo, pageSize, user.getId()).getResultData();
            if (portPayLog != null && portPayLog.size() > 0) {
                msg = "查询成功！";
            } else {
                msg = "无交易记录！";
            }
        } else {
            msg = "未查询到用户信息！";
        }
        return resultMsg.mapToJson(code, msg, portPayLog);
    }

    /**
     * 查询端口走势
     *
     * @param accessToken token
     * @return
     */
    @ApiOperation(value = " 查询端口走势", notes = "")
    @ApiImplicitParam(name = "accessToken", value = "token", required = true, dataType = "String")
    @ResponseBody
    @RequestMapping(value = "/ports/trend", method = RequestMethod.GET)
    public String trend(String accessToken, int portId) {
        UserInfo user = userDao.getUserByToken(accessToken);
        String code = "2";
        String msg = "处理异常！";
        List<PortPayLog> portPayLog = new ArrayList<PortPayLog>();
        Map<String, Object> result = new HashMap<>();
        if (user != null) {
            user.setPassword("");
            user.setSalt_value("");
            code = "1";
            portPayLog = portPayLogDAO.findPagination("from PortPayLog where portId = ?", 1, Integer.MAX_VALUE, portId).getResultData();
            if (portPayLog != null && portPayLog.size() > 0) {
                long[] price = new long[portPayLog.size()];
                Date[] date = new Date[portPayLog.size()];
                for (int i = 0; i < portPayLog.size(); i++) {
                    price[i] = portPayLog.get(i).getPrice();
                    date[i] = portPayLog.get(i).getDate();
                }
                result.put("price", price);
                result.put("date", date);
                msg = "查询成功！";
            } else {
                msg = "无交易记录！";
            }
        } else {
            msg = "未查询到用户信息！";
        }
        return resultMsg.mapToJson(code, msg, result);
    }

    /**
     * 获取端口配置信息
     *
     * @return
     */
    @ApiOperation(value = " 获取端口配置信息", notes = "")
    @ResponseBody
    @RequestMapping(value = "/ports/setting", method = RequestMethod.GET)
    public String portssetting() {
        String code = "1";
        String msg = "获取成功！";
        PortSetting portSetting = portSettingDAO.findAll().get(0);
        return resultMsg.mapToJson(code, msg, portSetting);
    }

    /**
     * 修改图片
     *
     * @return
     */
    @ApiOperation(value = " 修改图片", notes = "")
    @ResponseBody
    @RequestMapping(value = "/ports/updatePic", method = RequestMethod.GET)
    public String updatePic(int id, String pic) {
        String code = "1";
        String msg = "获取成功！";

        Port p = portDao.findByPortId(id);
        p.setCertificate_pic_url(pic);
        portDao.update(p);
        return resultMsg.mapToJson(code, msg, null);
    }


    /**
     * 修改指定端口 改为线下交易
     *
     * @param accessToken
     * @param portId
     * @return
     */
    @ApiOperation(value = " 修改端口出售状态", notes = "")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "accessToken", value = "token", required = true, dataType = "String"),
            @ApiImplicitParam(name = "portId", value = "端口id", required = true, dataType = "Integer")
    })
    @ResponseBody
    @RequestMapping(value = "/ports/updateSaleIng", method = RequestMethod.GET)
    public String updateSaleIng(String accessToken,Integer portId) {
        UserInfo user = userDao.getUserByToken(accessToken);
        String code = "2";
        String msg = "处理异常！";
        if (user != null) {
            Port p = portDao.findByPortId(portId);
            if(p == null){
                code = "2";
                msg = "处理异常！";
            }
            //修改为0 未出售 和线下交易
            p.setSaleing(0);
            p.setSource("offline");
            p.setType("offline");
            portDao.saveOrUpdate(p);
            code = "1";
            msg = "修改成功！";
        } else {
            msg = "未查询到用户信息！";
        }
        return resultMsg.mapToJson(code, msg, null);

    }

}